<template>
    <div class="loan-calculator-container">
      <el-card class="calculator-card">
        <template #header>
          <div class="card-header">
            <h2>贷款计算器</h2>
          </div>
        </template>
  
        <el-form :model="form" label-width="150px" label-position="left" class="centered-form">
          <el-form-item label="贷款类型">
            <el-radio-group v-model="form.loanType">
              <el-radio-button label="等额本息" />
              <el-radio-button label="等额本金" />
            </el-radio-group>
          </el-form-item>
  
          <el-form-item label="贷款金额">
            <el-input-number
              v-model="form.principal"
              :min="1000"
              :max="10000000"
              :step="1000"
              controls-position="right"
            />
            <span class="unit">元</span>
          </el-form-item>
  
          <el-form-item label="年利率">
            <el-input-number
              v-model="form.annualRate"
              :min="1"
              :max="20"
              :step="0.1"
              controls-position="right"
            />
            <span class="unit">%</span>
          </el-form-item>
  
          <el-form-item label="贷款年限">
            <el-input-number
              v-model="form.years"
              :min="1"
              :max="30"
              controls-position="right"
            />
            <span class="unit">年</span>
          </el-form-item>
  
          <el-form-item label="首次还款年月">
            <el-date-picker
              v-model="form.firstPaymentDate"
              type="month"
              placeholder="选择年月"
              value-format="YYYY-MM"
            />
          </el-form-item>          <el-form-item class="button-group">
            <div class="button-container">
              <el-button type="primary" @click="calculate">计算</el-button>
              <el-button @click="reset">重置</el-button>
            </div>
          </el-form-item>
        </el-form>
  
        <div v-if="result.show" class="result-section">
          <h3>计算结果</h3>
          <el-divider />
  
          <div class="summary">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-statistic 
                  title="每月还款" 
                  :value="result.firstMonthlyPayment" 
                  :precision="2"
                />
              </el-col>
              <el-col :span="8">
                <el-statistic 
                  title="总利息" 
                  :value="result.totalInterest" 
                  :precision="2"
                />
              </el-col>
              <el-col :span="8">
                <el-statistic 
                  title="还款总额" 
                  :value="result.totalPayment" 
                  :precision="2"
                />
              </el-col>
            </el-row>
          </div>
  
          <el-table
            :data="result.paymentSchedule"
            style="width: 100%; margin-top: 20px; font-size: 14px"
            stripe
            height="400"
            header-cell-class-name="custom-header"
            cell-class-name="custom-cell"
          >
            <el-table-column prop="period" label="期数" align="center" min-width="60" />
            <el-table-column prop="date" label="还款日期" align="center" min-width="100" />
            <el-table-column prop="monthlyPayment" label="月供(元)" align="right" min-width="100" />
            <el-table-column prop="principal" label="本金(元)" align="right" min-width="100" />
            <el-table-column prop="interest" label="利息(元)" align="right" min-width="100" />
            <el-table-column prop="remainingPrincipal" label="剩余本金(元)" align="right" min-width="120" />
            <el-table-column prop="remainingInterest" label="剩余利息(元)" align="right" min-width="120" />
          </el-table>
        </div>
      </el-card>
    </div>
  </template>
  
  <script setup>
  import { ref } from 'vue'
  
  const form = ref({
    loanType: '等额本息',
    principal: 100000,   // 更有意义的默认值
    annualRate: 4.9,     // 常见贷款利率
    years: 10,           // 常见贷款年限
    firstPaymentDate: new Date().toISOString().slice(0, 7) // 默认当前年月
  })
  
  const result = ref({
    show: false,
    firstMonthlyPayment: 0,
    totalInterest: 0,
    totalPayment: 0,
    paymentSchedule: []
  })
  
  // 添加月份
  const addMonths = (dateStr, months) => {
    const [year, month] = dateStr.split('-').map(Number)
    const date = new Date(year, month - 1, 1)
    date.setMonth(date.getMonth() + months)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
  }
  
  // 计算还款计划
  const calculateRepaymentSchedule = () => {
    const principal = form.value.principal
    const annualRate = form.value.annualRate
    const years = form.value.years
    const months = years * 12
    const monthlyRate = (annualRate / 100) / 12
    const firstPaymentDate = form.value.firstPaymentDate
  
    if (form.value.loanType === '等额本息') {
      // 等额本息计算
      const monthlyPayment = (principal * monthlyRate * Math.pow(1 + monthlyRate, months)) / 
                           (Math.pow(1 + monthlyRate, months) - 1)
      const totalPayment = monthlyPayment * months
      const totalInterest = totalPayment - principal
      
      const schedule = []
      let remainingPrincipal = principal
      
      for (let k = 1; k <= months; k++) {
        const dateStr = addMonths(firstPaymentDate, k - 1)
        const interest = remainingPrincipal * monthlyRate
        const principalPaid = monthlyPayment - interest
        remainingPrincipal -= principalPaid
        
        // 处理最后一个月可能出现的微小误差
        if (k === months) {
          remainingPrincipal = 0
        }
        
        schedule.push({
          period: k,
          date: dateStr,
          monthlyPayment: monthlyPayment.toFixed(2),
          principal: principalPaid.toFixed(2),
          interest: interest.toFixed(2),
          remainingPrincipal: Math.max(0, remainingPrincipal).toFixed(2),
          remainingInterest: Math.max(0, totalInterest - schedule.reduce((sum, item) => sum + parseFloat(item.interest), 0)).toFixed(2)
        })
      }
      
      return {
        firstMonthlyPayment: monthlyPayment,
        totalInterest,
        totalPayment,
        schedule
      }
    } else {
      // 等额本金计算
      const monthlyPrincipal = principal / months
      let totalInterest = 0
      const schedule = []
      let remainingPrincipal = principal
      
      for (let k = 1; k <= months; k++) {
        const dateStr = addMonths(firstPaymentDate, k - 1)
        const interest = remainingPrincipal * monthlyRate
        const monthlyPayment = monthlyPrincipal + interest
        totalInterest += interest
        remainingPrincipal -= monthlyPrincipal
        
        // 处理最后一个月可能出现的微小误差
        if (k === months) {
          remainingPrincipal = 0
        }
        
        schedule.push({
          period: k,
          date: dateStr,
          monthlyPayment: monthlyPayment.toFixed(2),
          principal: monthlyPrincipal.toFixed(2),
          interest: interest.toFixed(2),
          remainingPrincipal: Math.max(0, remainingPrincipal).toFixed(2),
          remainingInterest: Math.max(0, totalInterest - schedule.reduce((sum, item) => sum + parseFloat(item.interest), 0)).toFixed(2)
        })
      }
      
      const totalPayment = principal + totalInterest
      
      return {
        firstMonthlyPayment: schedule[0].monthlyPayment,
        totalInterest,
        totalPayment,
        schedule
      }
    }
  }
  
  const calculate = () => {
    const calculation = calculateRepaymentSchedule()
    result.value = {
      show: true,
      firstMonthlyPayment: calculation.firstMonthlyPayment,
      totalInterest: calculation.totalInterest,
      totalPayment: calculation.totalPayment,
      paymentSchedule: calculation.schedule
    }
  }
  const reset = () => {
    form.value = {
      loanType: '等额本息',
      principal: 100000, // 设置更有意义的默认值
      annualRate: 4.9,   // 设置常见贷款利率
      years: 10,         // 设置常见贷款年限
      firstPaymentDate: new Date().toISOString().slice(0, 7)
    }
    result.value = {
      show: false,
      firstMonthlyPayment: 0,
      totalInterest: 0,
      totalPayment: 0,
      paymentSchedule: []
    }
  }
  </script>
  
  <style scoped>
  .loan-calculator-container {
    max-width: 1000px;
    margin: 20px auto;
    padding: 20px;
  }

  .calculator-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 10px 0;
  }

  .card-header {
    text-align: center;
    margin-bottom: 20px;
  }

  .card-header h2 {
    font-size: 24px;
    font-weight: 600;
    color: var(--neutral-800);
    margin: 0;
    padding: 10px 0;
  }

  /* 表单样式优化 */
  .centered-form {
    max-width: 480px;
    margin: 0 auto;
    padding: 20px 0;
  }

  .centered-form :deep(.el-form-item) {
    width: 100%;
    margin-bottom: 20px;
  }

  .centered-form :deep(.el-form-item__label) {
    font-weight: 500;
    color: var(--neutral-800);
  }

  /* 输入控件统一宽度 */
  .centered-form :deep(.el-input-number),
  .centered-form :deep(.el-date-editor) {
    width: 200px;
  }

  /* 单位样式 */
  .unit {
    margin-left: 10px;
    color: var(--neutral-800);
    font-weight: 500;
  }

  /* 按钮组样式 */
  .button-container {
    display: flex;
    justify-content: center;
    width: 100%;
    padding: 10px 0;
  }

  .centered-form :deep(.button-group .el-form-item__content) {
    margin-left: 0 !important;
    justify-content: center;
    width: 100%;
  }

  .centered-form :deep(.el-button) {
    min-width: 120px;
    margin: 0 15px;
    height: 40px;
    font-size: 16px;
    font-weight: 500;
  }

  /* 单选按钮组居中 */
  .centered-form :deep(.el-radio-group) {
    display: flex;
    justify-content: center;
  }

  /* 结果区域样式 */
  .result-section {
    margin-top: 20px;
  }

  .summary {
    margin-bottom: 20px;
  }

  .el-statistic {
    text-align: center;
  }

  :deep(.el-statistic__content) {
    font-size: 20px;
    color: #409eff;
  }

  /* 表格样式 */
  .el-table {
    --el-table-border-color: #f0f0f0;
  }

  .custom-header {
    background-color: #fafafa;
    font-weight: 600;
    color: #333;
  }

  .custom-cell {
    color: #444;
  }
  </style>